package io.renren.modules.jxgk.util;


import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * Created by Administrator on 2017/11/20 0020.
 */
public class ImageFile {

    public final static String saveImage(HttpServletRequest request, MultipartFile file)
    {
        String urlofit="";
        String name= null;
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                String filename = file.getOriginalFilename();
                String prefix=filename.substring(filename.lastIndexOf("."));
                name=UUID.randomUUID().toString()+prefix;
                // 文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
                        + name;
                // 转存文件

                File filepath = new File(filePath, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                file.transferTo(new File(filePath));
                urlofit=filePath;
                return name;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return name;
    }
}
